package com.gjszn.kh.init;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.ServletContext;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;

import com.gjszn.kh.context.MemberContext;
import com.gjszn.kh.context.MemberRCodeContext;
import com.gjszn.kh.model.Member;
import com.gjszn.kh.model.RecommendationCode;
import com.gjszn.kh.service.MemberService;
import com.gjszn.kh.service.RecommendationCodeSerivce;


/**
 *  在项目初始化时，执行一下变量保存等操作
 * @author antj
 *
 */
public class InitDataLinstener implements InitializingBean, ServletContextAware {
	
	private static Logger logger = LogManager.getRootLogger();
	
	@Inject
	private MemberService memberService;
	
	@Inject
	private RecommendationCodeSerivce recommendationCodeSerivce;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		logger.info("初始化数据开始**************************");
		Map<String, Member> memberMap = new HashMap<String, Member>();
		List<Member> members = memberService.list();
		for(Member member : members){
			memberMap.put(member.getNumber(), member);
		}
		MemberContext.setMemberMap(memberMap);
		servletContext.setAttribute("memberMap", memberMap);
		logger.info("会员信息初始化完成**************************" + members.size());
		List<RecommendationCode> rcodes = recommendationCodeSerivce.getAll();
		for(RecommendationCode rcode : rcodes){
			MemberRCodeContext.add(rcode);
		}
		logger.info("推荐码信息初始化完成**************************" + rcodes.size());
		logger.info("初始化数据结束***********" + members.size()+ "***************");
	}
}